<template>
  <div>
    用户列表
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="25">
        <!-- 搜索区域     -->
        <el-col :span="10">
          <el-input
            placeholder="请输入搜索内容"
            clearable
            @clear="getUserList"
            v-model="queryInfo.query"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getUserList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 搜索按钮 -->
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户
          </el-button>
        </el-col>
        <el-col :span="4">
          <!-- 搜索按钮 -->
          <el-button
            type="primary"
            v-if="roleStyle"
            @click="addManagerDialogVisible = true"
            >添加管理员
          </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 border边框，stripe隔行变色 -->
      <el-table :data="userList" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="password" label="密码"> </el-table-column>
        <el-table-column prop="role" label="角色"> </el-table-column>
        <el-table-column prop="state" label="状态">
          <!-- 作用域插槽 -->
          <template v-slot="scope">
            <!-- {{ scope.row }} 每一行封存的数据 -->
            <el-switch
              :disabled="roleStyle==false"
              v-model="scope.row.state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updateVisible(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 权限 -->
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 size-change 每页最大变化 current-change 当前最大变化 layout功能组建-->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增用户区域 -->
    <el-dialog
      title="添加用户"
      v-model="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增管理员区域 -->
    <el-dialog
      title="添加管理员"
      v-model="addManagerDialogVisible"
      width="50%"
      @close="addManagerDialogClosed"
    >
      <el-form
        :model="addManagerForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addManagerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addManagerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addManagerForm.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addManagerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addManager">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改用户区 -->
    <el-dialog
      title="修改用户"
      v-model="updateDialogVisible"
      width="50%"
      @close="updateDialogClosed"
    >
      <el-form
        :model="updateForm"
        ref="updateFormRef"
        label-width="70px"
        :rules="updateFormrules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="updateForm.role"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="updateForm.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //查询信息实体
      queryInfo: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 5, //每页最大数
      },
      userList: [], //用户列表
      total: 0, //总记录数
      addDialogVisible: false, //对话框隐藏显示状态
      addManagerDialogVisible: false,
      updateDialogVisible: false,
      //添加表单信息
      addForm: {
        username: "",
        password: "",
        email: "",
      },
      addManagerForm: {
        username: "",
        password: "",
        email: "",
      },
      //更新表单信息
      updateForm: {
        id: 0,
        username: "",
        password: "",
        email: "",
        role: "",
      },
      //表单验证
      addFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 5, max: 40, message: "输入正确邮箱地址", trigger: "blur" },
        ],
      },
      //修改表单验证
      updateFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 5, max: 15, message: "输入正确邮箱地址", trigger: "blur" },
        ],
      },
      //用户角色
      roleStyle: false,
    };
  },
  created() {
    let role = window.sessionStorage.getItem("role");
    this.roleStyle = role == "超级管理员" ? true : false;
    this.getUserList();
  },
  methods: {
    //获取全部用户信息
    async getUserList() {
      // 调用post请求
      const { data: res } = await this.$http.get("allUser", {
        params: this.queryInfo,
      });
      console.log(res)
      this.userList = res.data.data; // 将返回数据赋值
      this.total = res.data.numbers; // 总个数
    },
    //最大数
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },
    //pageNum的触发动作
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },
    async userStateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `updateState?id=${userInfo.id}&state=${userInfo.state}`
      );
      console.log(res);
      if (res.data != "success") {
        userInfo.id = !userInfo.id;
        return this.$message.error("操作失败");
      }
      this.$message.success("操作成功");
    },
    //监听添加用户的操作
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addManagerDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    updateDialogClosed() {
      this.$refs.updateFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("addUser", this.addForm);
        if (res.data != "success") return this.$message.error("操作失败");
        this.$message.success("操作成功");
        this.addDialogVisible = false;
        this.getUserList;
      });
    },
    addManager() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "addManager",
          this.addManagerForm
        );
        if (res.data != "success") return this.$message.error("操作失败");
        this.$message.success("操作成功");
        this.addManagerDialogVisible = false;
        this.getUserList;
      });
    },
    //根据主键删除用户信息
    async deleteUser(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除用户，是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("deleteUser?id=" + id);
      if (res.data != "success") {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUserList();
    },
    updateVisible(userInfo) {
      (this.updateDialogVisible = true),
        (this.updateForm.username = userInfo.username),
        (this.updateForm.password = userInfo.password),
        (this.updateForm.email = userInfo.email),
        (this.updateForm.role = userInfo.role);
      this.updateForm.id = userInfo.id;
    },
    async updateUser() {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "updateUser",
          this.updateForm
        );
        console.log(this.updateForm);
        if (res.data != "success") return this.$message.error("操作失败");
        this.$message.success("操作成功");
        this.updateDialogVisible = false;
        this.getUserList();
      });
    },
  },
};
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
</style>
